<?php
/**
*[验证码类]
*/

//流程：
//①：创建画布
//②：获取验证码
//③：把验证码文字写入到画布中
//④：画线和画像素点


class Code
{
	// 设置变量
	public $width = 100;
	public $height = 30;
	public $color;
	public $img;
	public $str = 'qwiunekjurhygnkfolpkcbvxgfzdase2098756745320947124bvdgftreimglkxal';
	public $code;
	public $len = 5;
	public $fontFile = 'font.ttf';
	public $textSize=16;



	/**
	 * [构造函数]
	 */
	public function __construct()
	{
		
	}

	public function show()
	{	//创建画布
		$this->setImg();
		// 获取验证码
		$this->setcreatStr();
		// 把验证码写入到画布里面
		$this->setcreateText();
		//画线和像素点
		$this->setcreateLine();

		header('Content-type:image/png');
		imagepng($this->img);
	}



	// 创建画布
	/**
	 * [创建画布]
	 */
	private function setImg()
	{
		// 画布的大小
		$this->img = imagecreatetruecolor($this->width, $this->height);
		// 设置颜色
		$this->color = imagecolorallocate($this->img, 255, 255, 255);
		// 填充颜色
		imagefill($this->img, 0, 0, $this->color);

	}

	/**
	 * [获取验证码字符串]
	 * @return [type] [description]
	 */
	private function setcreatStr()
	{	
		// 创建空变量
		$code='';
		// 循环获取字符串
		for ($i=0; $i < $this->len; $i++) { 
			$num = mt_rand(0,strlen($this->str)-1);
			$code.=$this->str[$num];
		}
		//转大写
		$this->code = strtoupper($code);


	}


	/**
	 * [把验证码写入到画布中]
	 * @return [type] [description]
	 */
	private function setcreateText()
	{	
		// 平均分布字体
		$w = $this->width/$this->len;

		$this->color = imagecolorallocate($this->img, 0, 0, 255);
		// 循环输出字体
		for ($i=0; $i < $this->len; $i++) { 

			imagettftext($this->img, $this->textSize, mt_rand(-20,20), $w*$i+5, 20+mt_rand(0,10), $this->color, $this->fontFile, $this->code[$i]);
			
		}


	}

	/**
	 * [往画布里面画线和像素点]
	 * @return [type] [description]
	 */
	private function setcreateLine()
	{
		$this->color=imagecolorallocate($this->img, 0, 255, 0);

		// 随机画线
		for ($i=0; $i < 5; $i++) { 
			imageline($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), mt_rand(0,$this->width), mt_rand(0,$this->height), $this->color);
		}
		// 随机画点
		
		for ($i=0; $i < 100; $i++) { 

			imagesetpixel($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), $this->color);
		}
	}


	/**
	 * [获取颜色对象]
	 * @param string $value [转16进制]
	 */
	private function getColor($color)
	{	
		//#bcbcbc 先截取字符串 用
		$red = hexdec(substr($color, 1,2));
		$green = hexdec(substr($color, 3,2));
		$blue = hexdec(substr($color, 5,2));
	}


}



?>